package com.snail.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.snail.model.pojo.SysPermission;
import com.snail.response.BaseResponse;
import com.snail.response.ResultUtils;
import com.snail.service.SysPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author 蔡徐坤
 * @Date 2025/7/16 16:32
 * @Description: 用户对应的权限管理接口
 */
@RequestMapping("/permission")
@RestController
public class SysPermissionController {

    @Autowired
    private SysPermissionService permissionService;

    /**
     * 获取当前登录用户的菜单树
     */
    @GetMapping("/getUserMenu")
    public BaseResponse<List<SysPermission>> getUserMenu() {
        Long userId = StpUtil.getLoginIdAsLong(); // 获取当前登录用户ID
        List<SysPermission> menus = permissionService.getUserMenuTree(userId);
        return ResultUtils.success(menus);
    }

    /**
     * 获取所有菜单
     */
    @GetMapping("/allMenu")
    public BaseResponse<List<SysPermission>> getAllMenu() {
        List<SysPermission> list = permissionService.list();
        return ResultUtils.success(list);
    }

    /**
     * 新增菜单
     */
    @PostMapping("/addMenu")
    public BaseResponse<String> addMenu(@RequestBody SysPermission permission) {
        permissionService.save(permission);
        return ResultUtils.success("菜单添加成功");
    }

    /**
     * 修改菜单
     */
    @PutMapping("/updateMenu")
    public BaseResponse<String> updateMenu(@RequestBody SysPermission permission) {
        permissionService.updateById(permission);
        return ResultUtils.success("菜单更新成功");
    }

    /**
     * 删除菜单（逻辑删除）
     */
    @DeleteMapping("/deleteMenu/{id}")
    public BaseResponse<String> deleteMenu(@PathVariable Long id) {
        permissionService.deleteMenuAndRolePermission(id);
        return ResultUtils.success("菜单删除成功");
    }

    /**
     * 查询菜单（根据 ID）
     */
    @GetMapping("/getMenuById/{id}")
    public BaseResponse<SysPermission> getMenuById(@PathVariable Long id) {
        SysPermission permission = permissionService.getById(id);
        return ResultUtils.success(permission);
    }
}
